<template>
  <div>
    <divider>演示部分</divider>
    <ul>
      <li>
        <button id="eventLoop" @click="eventLoopHandler">Event Loop实践</button>
      </li>
    </ul>
    <ul>
      <li>
        <button id="wokerPostMessage" @click="workerPostMessageHandler">Web Worker通信</button>
      </li>
    </ul>
    <divider>文档部分</divider>
    <div id="md"></div>
  </div>
</template>

<script>

import { Divider } from 'ant-design-vue'
import md from '@/markdowns/jsBase-eventLoop.md'
import TestWorker from '@/workers/jsBase-eventLoop.worker.js'

export default {
  name: 'jsBase-eventLoop',
  components: {
    Divider
  },
  data () {
    return {
      
    }
  },
  watch: {
    
  },
  computed: {
    
  },
  methods: {
    eventLoopHandler () {
      console.log('本地-同步任务')
            
      setTimeout(() => {
        console.log('本地-宏任务-setTimeout 0')
      }, 0)
      setTimeout(() => {
        Promise.resolve().then((res) => {
          console.log('本地-宏任务中的微任务 - Promise in setTimeout 0')
        })
      }, 0)
      
      setTimeout(() => {
        Promise.resolve().then((res) => {
          console.log('本地-宏任务中的微任务 - Promise in setTimeout 1000')
        })
        console.log('本地-宏任务-setTimeout 1000')
      }, 1000)
      
      Promise.resolve().then((res) => {
        console.log('本地-微任务-Promise 1')
      })
      
      Promise.resolve().then((res) => {
        setTimeout(() => {
          console.log('本地-微任务中的宏任务 - setTimeout 0 in Promise 2')
        }, 0)
        setTimeout(() => {
          console.log('本地-微任务中的宏任务 - setTimeout 1000 in Promise 2')
        }, 1000)
        console.log('本地-微任务-Promise 2')
      })
      
      const worker = new TestWorker()
      console.log('读取Worker', worker)
      // 如果此时终止worker，worker中的任务会来不及执行
      // worker.terminate()
    },
    
    workerPostMessageHandler () {
      const worker = new TestWorker()
      worker.addEventListener('message', (e) => {
        console.log('收到worker回传：' + e.data)
        worker.terminate()
      })
      const msg = '25464646216'
      console.log('发送数据：' + msg)
      worker.postMessage(msg)
    }
  },
  created () {
    
  },
  mounted () {
    this.$el.querySelector('#md').innerHTML = this.$md(md)
  },
}
  
</script>

<style>
</style>
